import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/reg_new_qr.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/screens/mine/login_page.dart';
import 'package:mall/screens/mine/qrcode_page.dart';
import 'package:provider/provider.dart';

/// 扫码注册容器
class ScanRegisterContainer extends StatelessWidget {
  final Widget child;

  const ScanRegisterContainer({
    Key key,
    this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _onTap(context),
      child: Container(
        child: child,
      ),
    );
  }

  /// 点击注册
  void _onTap(BuildContext context) async {
    debugPrint("_onTap");
    // 扫码
    final text = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => QrcodePage(),
      ),
    );
    debugPrint("text = $text");
    if (text == null) {
      return;
    }
    try {
      // 解析
      final uri = Uri.parse(text);
      final queryParameters = uri.queryParameters;
      final encodedClientId = queryParameters['client_id'];
      final invitedCode = queryParameters['ic'];
      if (encodedClientId == null || invitedCode == null) {
        throw '无效二维码';
      }
      // 注册
      final auth = context.read<Auth>();
      EasyLoading.show();
      final regNewQr = await auth.regNewQr(encodedClientId, invitedCode);
      EasyLoading.dismiss();
      _showAlertDialog(context, regNewQr);
    } catch (e) {
      EasyLoading.showToast("无效二维码");
    }
  }

  /// 提示
  void _showAlertDialog(BuildContext context, RegNewQr regNewQr) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("注册成功"),
          content: Text('用户名：${regNewQr.username}\n密码：${regNewQr.originPassword}'),
          actions: [
            FlatButton(
              onPressed: () => _naviToLogin(context, regNewQr),
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }

  /// 导航到登录页面
  void _naviToLogin(BuildContext context, RegNewQr regNewQr) {
    Navigator.of(context).pushReplacementNamed(
      LoginPage.routeName,
      arguments: regNewQr.username,
    );
  }
}
